<template>
	<el-row  class="samples-container">
    <el-col :span="codeVisible ? 10 : 0">
      <codemirror-editor 
        :code="contentText"
        @codeChange="codeChange"
      />
    </el-col>
    <el-col :span="codeVisible ? 14 : 24" class="samples-render">
      <div class="code-operate" @click="codeVisible = !codeVisible">
        <el-image :src="codeVisible === false ? open : fold" class="code-operate-icon"></el-image>
      </div>
      <iframe 
        :src="contentText" 
        unselectable="on" 
        frameborder="0" 
        scrolling="no" 
        ref="renderer" 
        allowfullscreen
        style="width: 100%;height: 100%;"
      >
      </iframe>
    </el-col>
	</el-row >
  
  <!-- 可拖拽缩放 -->
  <!-- <ResizablePane :defaultCodeWidth="defaultCodeWidth" :minCodeWidth="minCodeWidth">
    <template #code>
      <ExperienceEditor :code="contentText" @codeChange="codeChange" />
    </template>
    <template #render>
      <iframe
        :src="contentText"
        unselectable="on"
        frameborder="0"
        scrolling="no"
        ref="renderer"
        allowfullscreen
        style="width: 100%; height: 100%;"
      ></iframe>
    </template>
  </ResizablePane> -->

</template>
 
<script setup>
  import { ref, onMounted, watch } from 'vue';
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
	import { CodemirrorEditor } from './index.js';
  import fold from '@/assets/images/fold.png';
  import open from '@/assets/images/open.png';

  const route = useRoute()
  const defaultCodeWidth = 500
  const minCodeWidth = 0
  const codeVisible = ref(true)
  const renderer = ref(null)
  const contentText = ref(null)
  const sourceCodePath = ref(null)

  onMounted(() => {
    codePath()
  })
  
  // 代码路径
  const codePath = async () => {
    try {
      const code = await fetch(`examples/${sourceCodePath.value}.html`);
      // const code = await fetch('../src/views/Demo/examples/1-1.vue');
      contentText.value = await code.text();
      codeChange(contentText.value);
    } catch (error) {
      console.error(error);
      ElMessage.warning(error);
    }
  }
  // 向iframe空页面写代码
  const codeChange = (code) => {
    const iframe = renderer.value;
    iframe.contentDocument.open();
    iframe.contentDocument.write(code);
    iframe.contentDocument.close();
  }
  watch(
		() => route.params.id,
		(newValue, oldValue) => {
      sourceCodePath.value = newValue.substr(newValue.indexOf(":") + 1, newValue.length);
      codePath()
		},
    {
      immediate: true
    }
	)
</script>

<style lang="scss" scoped>
.samples-container {
  height: 100vh;
  .samples-render {
    position: relative;
    .code-operate {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      &-icon {
        width: 40px;
        &:hover {
          height: 100px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>